package com.football.springboot.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.football.springboot.common.Constants;
import com.football.springboot.common.Return;
import com.football.springboot.entity.Files;
import com.football.springboot.mapper.FileMapper;
import com.football.springboot.service.IFilesService;
import com.football.springboot.vo.FileQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


@Api(tags = "文件管理")
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${server.ip}")
    private String serverIp;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private IFilesService filesService;

    //文件上传接口
    @ApiOperation("文件上传接口")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        //存储到磁盘
        File uploadParentFile = new File(fileUploadPath);
        // 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if(!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);

        String url;
        //获取文件的md5
        String md5 = SecureUtil.md5(file.getInputStream());

        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        if (dbFiles != null) {
            url = dbFiles.getUrl();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件，则不删除刚才上传的文件
            url = "http://" + serverIp + ":9090/file/" + fileUUID;
        }

        //存到数据库
        Files saveFile = new Files();

        // 存储数据库
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024); // 单位 kb
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);
        System.out.println(fileUploadPath);
        return url;

    }
    //通过文件的md5查询文件
    @ApiOperation("通过文件的md5查询文件")
    private Files getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }


    //文件下载接口   http://localhost:9090/file/{fileUUID}
    @ApiOperation("文件下载接口")
    @RequestMapping(value = "/{fileUUID}",method = RequestMethod.GET)
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }


    //更新文件
    @ApiOperation("更新文件")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Return update(@RequestBody Files files) {
        fileMapper.updateById(files);
        return Return.ok();
    }


    //获取单个文件信息
    @ApiOperation("获取单个文件信息")
    @RequestMapping(value = "/detail/{id}",method = RequestMethod.GET)
    public Return getById(@PathVariable Integer id) {

        return Return.ok().put("data",fileMapper.selectById(id));
    }



    //文件删除(只是修改isdelete的值)
    @ApiOperation("文件删除")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Return delete(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(1);
        //fileMapper.updateById(files);
        String code = "";
        Integer isdelete=fileMapper.updateById(files);
        if (isdelete==1){
            code=Constants.CODE_200;
        }else{
            code="";
        }
        return Return.ok().put("code", code);
    }
    //批量删除
    @ApiOperation("批量删除")
    @RequestMapping(value = "/del/batch",method = RequestMethod.POST)
    public Return deleteBatch(@RequestBody List<Integer> ids) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<Files> files = fileMapper.selectList(queryWrapper);
        String code = "";
        for (Files file : files) {
            file.setIsDelete(1);
            Integer isdelete=fileMapper.updateById(file);
            if (isdelete==1){
                code=Constants.CODE_200;
            }else{
                code="";
            }
        }
        return Return.ok().put("code", code);
    }

    //文件名查询加分页
    @ApiOperation("文件名查询加分页")
    @RequestMapping(value = "/PageFiles",method = RequestMethod.GET)
    public Return PageFiles(@RequestParam long current,
                           @RequestParam long limit,
                           FileQueryVo fileQueryVo) {
        //创建page对象，传递当前页数current，每页记录数limit
        Page<Files> page = new Page<>(current,limit);


        //构建条件 模糊查询
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();

        String name = fileQueryVo.getName();


        // 查询未删除的记录
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByDesc("id");

        //文件名查询
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByDesc("id");


        Page<Files> pageFiles = filesService.page(page,queryWrapper);
        return Return.ok().put("pageFiles",pageFiles).put("total",pageFiles.getTotal());
    }

}
